package com.lmabbe.common.datasources.handle;

import com.lmabbe.common.global.context.TenantBuildContext;
import com.lmabbe.common.global.context.metadata.dict.SystemDict;
import com.lmabbe.common.global.context.metadata.param.SystemParam;
import com.lmabbe.common.global.context.metadata.resource.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 初始化系统数据
 *
 * @author lmabbe
 */
@Slf4j
public class InitSystemDataHandle extends InitApplicationHandle {

    public InitSystemDataHandle(ApplicationContext applicationContext, TenantBuildContext tenantContext) {
        super(applicationContext, tenantContext);
    }

    @Override
    public void handle(InitApplicationContext context) {
        log.info(">>>>>>>>>初始化租户字典>>>>>>>");
        //初始化租户字典
        initSysDict(tenantContext.getSysDictionaries());
        log.info(">>>>>>>>>初始化系统参数>>>>>>>");
        //初始化系统参数
        initSysParams(tenantContext.getSystemParams());
        log.info(">>>>>>>>>初始化系统菜单>>>>>>>");
        //初始化系统菜单
        initSysMenu(tenantContext.getResources());
    }

    /**
     * 初始化菜单
     *
     * @param resources
     */
    private void initSysMenu(List<Resource> resources) {
        if (resources == null || resources.size() == 0) {
            return;
        }
        getInitResourceMapper().initResource(resources);
    }

    /**
     * 初始化系统字典
     *
     * @param sysDictionaries
     */
    private void initSysDict(List<SystemDict> sysDictionaries) {
        if (sysDictionaries == null || sysDictionaries.size() == 0) {
            return;
        }
        getInitSysDictMapper().initSysDict(sysDictionaries);
        List<SystemDict.Item> items = new ArrayList<>();
        sysDictionaries.stream().forEach(s -> items.addAll(s.getItems() == null ? new ArrayList<>() : s.getItems()));
        if(items.size() != 0){
            getInitSysDictMapper().initSysDictItem(items);
        }
    }

    /**
     * 初始化系统字典
     *
     * @date 2021/12/28 10:17 AM
     * @author liming
     */
    private void initSysParams(List<SystemParam> systemParams) {
        //初始化非强制更新的配置
        List<SystemParam> notForce = systemParams.stream().filter(s -> s.getForce() == null || !s.getForce()).collect(Collectors.toList());
        if (!notForce.isEmpty()) {
            getInitSysParamMapper().initSysParams(notForce);
        }
        //初始化强制更新的配置
        List<SystemParam> force = systemParams.stream().filter(s -> s.getForce() != null && s.getForce()).collect(Collectors.toList());
        if (!force.isEmpty()) {
            getInitSysParamMapper().delBatchIds(force.stream().map(s -> s.getParamId()).collect(Collectors.toList()));
            getInitSysParamMapper().initSysParams(force);
        }
    }


}
